<template>
	<view class="submitOrder">
		<view class="submitOrder_header">
			<view>
				<view class="item" v-for="(item, index) in data.addressData" :key="item.id" @click="jump">
					<view class="top">
						<view class="name">{{ item.name }}</view>
						<view class="phone">{{ item.phone_number }}</view>
					</view>
					<view class="bottom">
						{{ item.address }}
						<up-icon name="arrow-right" :size="20" color="#999999"></up-icon>
					</view>
				</view>
			</view>
		</view>
		<view class="submitOrder_content">
			<view class="submitOrder_content_product" v-for="(item, index) in data.product" :key="item.id">
				<view class="submitOrder_content_product_img">
					<image :src="item.image_url" mode=""></image>
				</view>
				<view class="submitOrder_content_product_text">
					<view class="submitOrder_content_product_name">
						{{ item.product_name }}
						<up-text :lines="3" :text="item.description"></up-text>
					</view>
					<view class="submitOrder_content_product_PAN">
						<view class="submitOrder_content_product_price">￥{{ calculatePrice(item) }}</view>
						<view class="submitOrder_content_product_num">x{{ item.quantity }}</view>
					</view>
				</view>
			</view>
			<view class="submitOrder_content_num">
				<view class="submitOrder_content_num_all">
					<view class="submitOrder_content_num_all_1">共{{ data.product.length }}件商品</view>
					<view class="submitOrder_content_num_all_2">合计</view>
					<view class="submitOrder_content_num_all_3">￥{{ totalPrice }}</view>
				</view>
			</view>
			<view class="submitOrder_content_offer">
				<view class="submitOrder_content_offer_1">优惠券:暂无可用</view>
				<view class="submitOrder_content_offer_1">买家信息:给卖家留言</view>
				<view class="submitOrder_content_offer_2">
					订单总额:
					<view class="submitOrder_content_offer_price">￥{{ totalPrice }}</view>
				</view>
				<view class="submitOrder_content_offer_2">
					运费:
					<view class="submitOrder_content_offer_price">￥0.00</view>
				</view>
				<view class="submitOrder_content_offer_2">
					优惠总额:
					<view class="submitOrder_content_offer_price">￥0.00</view>
				</view>
			</view>
		</view>
		<view class="submitOrder_bottom">
			<view class="submitOrder_bottom_account">
				合计:
				<view class="submitOrder_bottom_account_price">￥{{ totalPrice }}</view>
			</view>
			<view class="submitOrder_bottom_button" @click="submitOrder">
				<up-button text="提交订单" color="#ed7b49" size="large"></up-button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onMounted, getCurrentInstance, reactive, computed, watchEffect, watch } from 'vue';
import { GetShoppingDataFromId, GetUserFromId, GetShoppingAddressFromId, AddOrderItemsSchedule, AddOrders, DeleteShoppingData,ChangeShoppingInventory } from '../../apis/api.js';
import useCartStore from '../../store/index.js';
import getDetailedDateTime from '../../utils/time.js';

const data = reactive({
	product: [],
	addressData: [],
	address_id: '',
	order_id: '',
	time: getDetailedDateTime()
});

console.log(getDetailedDateTime());

const instance = getCurrentInstance().proxy;
console.log(instance.options.id);


const addressStore = useCartStore();

watch(() => {
	// 回去被选中的商品，假如到订单当中
	GetShoppingDataFromId({
		id: instance.options.id
	}).then((res) => {
		console.log(res);
		if (res.msgType == 8000) {
			data.product = res.data;
			console.log(data.product);
		} else {
		}
	});
});

// 去除金额处理不清
function calculatePrice(item) {
	return (item.price * item.quantity).toFixed(2);
}

// 计算总金额
const totalPrice = computed(() => {
	let sum = 0;
	data.product.forEach((item) => {
		sum += parseFloat(item.price * item.quantity);
	});
	return sum.toFixed(2);
});
console.log(totalPrice);

// 获取用户地址
// 获取收货人地址信息
onMounted(() => {
	uni.getStorage({
		key: 'userId',
		success: async (res) => {
			data.user_id = res.data;
			console.log('获取的 userId 为：', data.user_id);

			addressStore.initAddressId(data.user_id);
			watchEffect(() => {
				GetShoppingAddressFromId({
					address_id: addressStore.$state.addressId
				}).then((res) => {
					console.log(res);
					data.addressData = res.data;
				});
			});
		},
		fail: (error) => {
			console.error('获取 userId 失败：', error);
		}
	});
});

const submitOrder = () => {
	// 确认是否购买
	watch(() => {
		uni.showModal({
			title: '确认购买',
			content: '确定要购买商品吗？',
			success: function (res) {
				if (res.confirm) {
					// 确认提交购买
					AddOrders({
						shipping_address: data.addressData[0].address,
						phone: data.addressData[0].phone_number,
						name: data.addressData[0].name,
						user_id: data.user_id,
						total_amount: totalPrice.value,
						created_at: data.time,
						status: '待发货'
					}).then((res) => {
						console.log(res);
						if (res.msgType == 8000) {
							data.order_id = res.order_id;
							// 提交订单的商品信息
							data.product.forEach((item) => {
								console.log(item);
								// order_id, product_id, quantity, unit_price, subtotal_price;
								AddOrderItemsSchedule({
									order_id: data.order_id,
									product_id: item.product_id,
									quantity: item.quantity,
									unit_price: item.price,
									subtotal_price: calculatePrice(item),
									product_name:item.product_name,
									product_image:item.image_url,
									product_description:item.description,
									created_at:data.time
								}).then((res) => {
									console.log(res);
									if (res.msgType == 8000) {
										// 跳转到支付界面
										// 订单提交后，删除购物了的商品
										ChangeShoppingInventory({											
											inventory:item.quantity,
											product_id:item.product_id
										}).then(res=>{
											console.log(res);									
										})
										
										DeleteShoppingData({
											id: JSON.parse(instance.options.id)
										}).then((res) => {
											if (res.msgType == 8000) {
												addressStore.initBadge(data.user_id);
											}
										});
										uni.redirectTo({
											url: '/pages/payment/payment?pay=' + totalPrice.value
										});
									} else {
									}
								});
							});
						} else {
						}
					});
				} else {
					AddOrders({
						shipping_address: data.addressData[0].address,
						phone: data.addressData[0].phone_number,
						name: data.addressData[0].name,
						user_id: data.user_id,
						total_amount: totalPrice.value,
						created_at: data.time,
						status: '待支付'
					}).then((res) => {
						console.log(res);
						if (res.msgType == 8000) {
							data.order_id = res.order_id;
							// 提交订单的商品信息
							data.product.forEach((item) => {
								console.log(item);
								// order_id, product_id, quantity, unit_price, subtotal_price;
								AddOrderItemsSchedule({									
									order_id: data.order_id,
									product_id: item.product_id,
									quantity: item.quantity,
									unit_price: item.price,
									subtotal_price: calculatePrice(item),
									product_name:item.product_name,
									product_image:item.image_url,
									product_description:item.description,
									created_at:data.time
								}).then((res) => {
									console.log(res);
									if (res.msgType == 8000) {
										// 跳转到支付界面
										// 订单提交后，删除购物了的商品
										DeleteShoppingData({
											id: JSON.parse(instance.options.id)
										}).then((res) => {
											if (res.msgType == 8000) {
												addressStore.initBadge(data.user_id);
											}
										});
										//
										uni.switchTab({
											url: '/pages/cart/cart'
										});
									} else {
									}
								});
							});
						} else {
						}
					});
				}
			}
		});
	});
};

// 点击跳转到修改地址
const jump = () => {
	// 这里跳转传参可能会泄漏
	uni.navigateTo({
		url: '/pages/address/address'
	});
};
</script>

<style lang="less" scoped>
.item {
	margin-top: 10rpx;
	padding: 40rpx 20rpx;
	border: 1px solid #ccc;
	border-radius: 5px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
	.top {
		display: flex;
		font-weight: bold;
		font-size: 34rpx;
		.phone {
			margin-left: 60rpx;
		}
		.tag {
			display: flex;
			font-weight: normal;
			align-items: center;
			text {
				display: block;
				width: 60rpx;
				height: 34rpx;
				line-height: 34rpx;
				color: #ffffff;
				font-size: 20rpx;
				border-radius: 6rpx;
				text-align: center;
				margin-left: 30rpx;
				background-color: rgb(49, 145, 253);
			}
			.red {
				background-color: red;
			}
		}
	}
	.bottom {
		display: flex;
		margin-top: 20rpx;
		font-size: 28rpx;
		justify-content: space-between;
		color: #999999;
	}
}
.submitOrder {
	height: 100vh;

	.submitOrder_content {
		height: 550rpx;

		.submitOrder_content_product {
			display: flex;
			padding: 10rpx;
			border: 1px solid #ccc;
			border-radius: 5px;
			box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
			margin-bottom: 10rpx;
			// flex-direction: column;
			.submitOrder_content_product_img {
				width: 30%;
				height: 200rpx;
				image {
					width: 100%;
					height: 100%;
				}
			}
			.submitOrder_content_product_text {
				width: 70%;
				padding: 10rpx;
				.submitOrder_content_product_name {
					font-size: 40rpx;
				}
				.submitOrder_content_product_PAN {
					display: flex;
					justify-content: space-between;
					margin-top: 30rpx;
					.submitOrder_content_product_price {
						font-size: 35rpx;
					}
					.submitOrder_content_product_num {
						color: #999999;
					}
				}
			}
		}
		.submitOrder_content_num {
			// display: flex;
			height: 100rpx;
			border-radius: 5px;
			box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
			margin-bottom: 10rpx;
			.submitOrder_content_num_all {
				display: flex;
				justify-content: flex-end;
				.submitOrder_content_num_all_1,
				.submitOrder_content_num_all_2,
				.submitOrder_content_num_all_3 {
					padding-right: 15rpx;
					font-size: 32rpx;
					margin-top: 20rpx;
				}
			}
		}
		.submitOrder_content_offer {
			height: 300rpx;
			border: 2rpx solid red;
			margin-top: 25rpx;
			padding: 10rpx;
			border: 2rpx solid #ccc;
			border-radius: 5px;
			box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
			margin-bottom: 20rpx;
			padding-bottom: 50rpx;
			.submitOrder_content_offer_1 {
				height: 50rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border: 2rpx solid #ccc;
				border-radius: 5px;
				box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
			}
			.submitOrder_content_offer_2 {
				display: flex;
				justify-content: space-between;
				margin-top: 15rpx;
				font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
				.submitOrder_content_offer_price {
					font-size: 40rpx;
					color: #ed7b49;
				}
			}
		}
	}
	.submitOrder_bottom {
		height: 100rpx;
		width: 100%;
		border: 1px solid #ccc;
		border-radius: 5px;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
		position: fixed;
		bottom: 0;
		display: flex;
		background-color: #f0f0f0;
		.submitOrder_bottom_account {
			width: 65%;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			.submitOrder_bottom_account_price {
				color: red;
				font-size: 40rpx;
			}
		}
		.submitOrder_bottom_button {
			width: 35%;
		}
	}
}
</style>